<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>人脸注册 - 智慧考勤系统</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
    <style>
        .error-message {
            color: red;
            margin: 10px 0;
        }
        .success-message {
            color: green;
            margin: 10px 0;
        }
        .video-container {
            margin: 20px 0;
            position: relative;
            background: #f5f5f5;
            border: 1px solid #ddd;
            border-radius: 4px;
            overflow: hidden;
        }
        #video-status {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 10px;
            border-radius: 5px;
            display: none;
            z-index: 100;
        }
        .button-group {
            margin-top: 20px;
        }
        .button-group button {
            margin: 0 10px;
            padding: 10px 20px;
            cursor: pointer;
        }
        .button-group button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        .debug-info {
            margin-top: 10px;
            padding: 10px;
            background: #f0f0f0;
            border-radius: 4px;
            font-size: 0.9em;
            display: none;
        }
        #video {
            width: 100%;
            max-width: 640px;
            height: auto;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>人脸注册</h1>
            <p class="subtitle">请填写员工信息并完成人脸注册</p>
        </header>

        <main>
            <div class="card">
                <div id="error-container" class="error-message"></div>
                <div id="success-container" class="success-message"></div>

                <form id="registration-form">
                    <div class="form-group">
                        <label for="employee_id">员工ID：</label>
                        <input type="text" id="employee_id" name="employee_id" required>
                    </div>
                    <div class="form-group">
                        <label for="name">姓名：</label>
                        <input type="text" id="name" name="name" required>
                    </div>
                    <div class="form-group">
                        <label for="department">部门：</label>
                        <input type="text" id="department" name="department" required>
                    </div>
                    <div class="form-group">
                        <label for="position">职位：</label>
                        <input type="text" id="position" name="position" required>
                    </div>
                    
                    <div class="video-container">
                        <img id="video" src="{{ url_for('video_feed') }}" alt="摄像头画面">
                        <div id="video-status">正在连接摄像头...</div>
                        <canvas id="canvas" style="display:none;"></canvas>
                    </div>
                    
                    <div class="button-group">
                        <button type="submit" id="submit-btn" class="primary-btn">注册人脸</button>
                        <a href="/" class="secondary-btn">返回主页</a>
                    </div>
                </form>
                
                <div id="debug-info" class="debug-info"></div>
            </div>
        </main>
    </div>

    <script>
        const video = document.getElementById('video');
        const canvas = document.getElementById('canvas');
        const form = document.getElementById('registration-form');
        const submitBtn = document.getElementById('submit-btn');
        const videoStatus = document.getElementById('video-status');
        const errorContainer = document.getElementById('error-container');
        const successContainer = document.getElementById('success-container');
        const debugInfo = document.getElementById('debug-info');

        function showError(message) {
            errorContainer.textContent = message;
            errorContainer.style.display = 'block';
            successContainer.style.display = 'none';
            submitBtn.disabled = false;
        }

        function showSuccess(message) {
            successContainer.textContent = message;
            successContainer.style.display = 'block';
            errorContainer.style.display = 'none';
        }

        function showDebugInfo(info) {
            debugInfo.style.display = 'block';
            debugInfo.innerHTML += `<div>${new Date().toLocaleTimeString()}: ${info}</div>`;
        }

        // 检查视频流是否正常加载
        video.onload = function() {
            videoStatus.style.display = 'none';
            showDebugInfo('视频流加载成功');
        };

        video.onerror = function() {
            videoStatus.textContent = '视频流连接失败';
            videoStatus.style.display = 'block';
            showError('无法连接到摄像头视频流');
            showDebugInfo('视频流加载失败');
        };

        // 确保图像质量的函数
        function ensureImageQuality() {
            return new Promise((resolve, reject) => {
                // 等待视频流完全加载
                if (video.readyState < video.HAVE_CURRENT_DATA) {
                    showDebugInfo('等待视频流加载...');
                    video.addEventListener('loadeddata', () => {
                        setTimeout(resolve, 1000); // 等待1秒确保画面稳定
                    });
                } else {
                    resolve();
                }
            });
        }

        // 表单提交处理
        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            try {
                submitBtn.disabled = true;
                showSuccess('正在处理...');
                showDebugInfo('开始处理人脸注册...');

                // 等待确保图像质量
                await ensureImageQuality();

                //创建 Canvas 画布，将 video 当前帧画到 canvas 上。
                //连续捕获3帧图像，每帧间隔 100ms，减少捕获模糊图像的概率。
                //由于 canvas.toDataURL() 会返回最后一帧数据，因此默认使用最后一帧。
                // 捕获视频帧
                canvas.width = video.naturalWidth || 640;
                canvas.height = video.naturalHeight || 480;
                const ctx = canvas.getContext('2d');
                
                // 捕获多帧并使用质量最好的一帧
                for (let i = 0; i < 3; i++) {
                    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
                    await new Promise(resolve => setTimeout(resolve, 100)); // 间隔100ms
                }

                // 获取表单数据
                const formData = new FormData(form);
                
                // 将图像数据转换为Base64
                //这段代码生成的 Base64 编码 代表了 Canvas 中的图像数据（即捕获的头像）。
                // 它并不会直接存储到本地文件夹中，而是以 Base64 字符串的形式存在。
                //这个字符串会通过 formData.append('image', imageData) 被附加到表单数据中，
                // 并且作为 POST 请求的一部分，发送到后端的 /register_face 接口。

                const imageData = canvas.toDataURL('image/jpeg', 0.95);
                formData.append('image', imageData);

                try {
                    const response = await fetch('/register_face', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: new URLSearchParams(formData)
                    });

                    const result = await response.json();

                    if (result.success) {
                        showSuccess(result.message);
                        showDebugInfo('人脸注册成功');
                        setTimeout(() => {
                            window.location.href = '/';
                        }, 2000);
                    } else {
                        let errorMsg = result.message;
                         if (errorMsg.includes('该人脸已经注册')) {
                            errorMsg = '该人脸已经注册过，请勿重复注册';}
                       else if (errorMsg.includes('未检测到人脸')) {
                            errorMsg = '未能检测到清晰的人脸，请确保光线充足且正面对着摄像头';
                        } else if (errorMsg.includes('多个人脸')) {
                                 errorMsg = '检测到多个人脸，请确保画面中只有一个人脸';
                             }
                        showError(errorMsg);
                        showDebugInfo(`人脸注册失败: ${result.message}`);
                    }
                } catch (error) {
                    console.error('Error:', error);
                    showError('注册失败，请重试');
                    showDebugInfo(`注册过程错误: ${error.message}`);
                }
            } catch (error) {
                console.error('Error:', error);
                showError('注册失败，请重试');
                showDebugInfo(`注册过程错误: ${error.message}`);
            } finally {
                submitBtn.disabled = false;
            }
        });

        // 显示调试信息
        if (location.search.includes('debug=true')) {
            debugInfo.style.display = 'block';
        }
    </script>
</body>
</html> 